package com.wenjoying.user.controller;

import com.alibaba.fastjson.JSONObject;
import com.netflix.hystrix.contrib.javanica.annotation.HystrixCommand;
import com.wenjoying.user.service.feign.GoodsService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.context.config.annotation.RefreshScope;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMethod;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;
import com.wenjoying.common.api.BaseController;
import com.wenjoying.common.api.BaseException;
import com.wenjoying.common.api.CommonResult;

@RefreshScope
@RestController
@RequestMapping(value = "user/user")
public class UserController extends BaseController {
    @Autowired
    private RestTemplate restTemplate;

    @Autowired
    private GoodsService goodsService;

    @Autowired
    private HttpHeaders httpHeaders;

    @Value("${dataConfig.jwt.key:}")
    private String jwtKey;

    @HystrixCommand(fallbackMethod = "fallback")
    @RequestMapping(value = "testApi", method = RequestMethod.GET)
    public CommonResult testApi(@RequestBody JSONObject jsonObject){
        try {


            String url = "http://wenjoying.goods/goods/goods/testApi";
            ResponseEntity<JSONObject> res = restTemplate.exchange(url, HttpMethod.POST, new HttpEntity<>(jsonObject, httpHeaders),JSONObject.class);
            return CommonResult.success(res.getBody());
        } catch (Exception e) {
            throw new BaseException(e);
        }
    }

    @HystrixCommand(fallbackMethod = "fallback")
    @RequestMapping(value = "test1", method = RequestMethod.GET)
    public CommonResult test1(@RequestBody JSONObject jsonObject) {
        try {
            return CommonResult.success(goodsService.testApi(jsonObject));
        } catch (Exception e) {
            throw new BaseException(e);
        }
    }

    @RequestMapping(value = "test2", method = RequestMethod.GET)
    public CommonResult test2(String username) {
        try {
            System.err.println(jwtKey);
            JSONObject jsonObject = new JSONObject();
            jsonObject.put("jwtKey", jwtKey);
            jsonObject.put("username", username);
            return CommonResult.success(jsonObject);
        } catch (Exception e) {
            throw new BaseException(e);
        }
    }

    public CommonResult fallback(@RequestBody JSONObject jsonObject) {
        return CommonResult.failed("服务降级了^^");
    }
}
